package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.dto.supplier.ContractDto;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.StringUtils;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.BamuContractMaterial;
import com.yunyao.dao.model.BamuPurchaseApplyMaterial;
import com.yunyao.dao.service.bamu.IBamuContractMaterialService;
import com.yunyao.dao.service.bamu.IBamuPurchaseApplyMaterialService;
import com.yunyao.framework.dto.projectorder.ProjectMaterialSaveDto;
import com.yunyao.framework.service.ProjectMaterialService;
import com.yunyao.framework.vo.contract.ContractMaterialVO;
import com.yunyao.framework.vo.projectorder.ProjectMaterialVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author chenyejian
 * @date 2024-07-16
 */
@Slf4j
@Service
public class ProjectMaterialServiceImpl implements ProjectMaterialService {
    @Autowired
    private IBamuPurchaseApplyMaterialService bamuPurchaseApplyMaterialService;
    @Autowired
    private IBamuContractMaterialService iBamuContractMaterialService;
    @Override
    public YResult<PageResult<ProjectMaterialVO>> pageList(String orderId,Long pageIndex,Long pageSize) {
        if (StringUtils.isEmpty(orderId)) {
            return YResult.success(new PageResult<>());
        }
        LambdaQueryWrapper<BamuPurchaseApplyMaterial> queryWrapper = new LambdaQueryWrapper<BamuPurchaseApplyMaterial>();
        queryWrapper.eq(BamuPurchaseApplyMaterial::getPurchaseApplyId, orderId)
                .eq(BamuPurchaseApplyMaterial::getIsDeleted, DataDeletedStatus.NO.getType())
                .orderByAsc(BamuPurchaseApplyMaterial::getMaterialSortNum)
                .orderByAsc(BamuPurchaseApplyMaterial::getIsCopy);
        IPage<BamuPurchaseApplyMaterial> page = new Page<>(pageIndex, pageSize);
        page =bamuPurchaseApplyMaterialService.page(page, queryWrapper);
        return YResult.success(new PageResult<>(convertDao2VoList(page.getRecords()),pageIndex,pageSize,page.getPages(),page.getTotal()));
    }

    public YResult<PageResult<ContractMaterialVO>> getContractMaterialList(ContractDto contractDto) {
        // 构建查询条件
        String contractId = contractDto.getContractId();
        LambdaQueryWrapper<BamuContractMaterial> wrapper = new LambdaQueryWrapper<BamuContractMaterial>()
                .eq(StringUtils.isNotBlank(contractId), BamuContractMaterial::getContractId,
                        contractId)
                .eq(BamuContractMaterial::getIsDeleted, DataDeletedStatus.NO.getType())
                .like(StringUtils.isNotBlank(contractDto.getMaterialCode()), BamuContractMaterial::getMaterialCode,contractDto.getMaterialCode())
                .like(StringUtils.isNotBlank(contractDto.getMaterialName()),BamuContractMaterial::getMaterialName,contractDto.getMaterialName())
                .notIn(CollectionUtils.isNotEmpty(contractDto.getContractMaterialIdList()),
                        BamuContractMaterial::getId,contractDto.getContractMaterialIdList())
                .in(CollectionUtils.isNotEmpty(contractDto.getPurchaseContractMaterialIdList()),
                        BamuContractMaterial::getId,contractDto.getPurchaseContractMaterialIdList())
                .like(StringUtils.isNotBlank(contractDto.getMaterialSpecs()),BamuContractMaterial::getMaterialSpecs,contractDto.getMaterialSpecs())
                .orderByAsc(BamuContractMaterial::getMaterialSortNum)
                .orderByAsc(BamuContractMaterial::getId);
        // 分页查
        IPage<BamuContractMaterial> payPage = new Page<>(contractDto.getPageIndex(), contractDto.getPageSize());
        payPage = iBamuContractMaterialService.page(payPage, wrapper);

        if (payPage.getRecords()==null || payPage.getRecords().size()==0 || payPage.getTotal() == 0) {
            return YResult.success(new PageResult<>());
        }
        // 处理查询结果
        if (CollectionUtils.isEmpty(payPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<ContractMaterialVO> materialVOList = materialDaoToVoList(payPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(materialVOList, payPage.getCurrent(), payPage.getSize(), payPage.getPages(), payPage.getTotal()));
    }


    private List<ContractMaterialVO> materialDaoToVoList(List<BamuContractMaterial> records) {
        return records.stream().map(this::materialDaoToVo).collect(Collectors.toList());
    }

    private ContractMaterialVO materialDaoToVo(BamuContractMaterial bamuContractMaterial) {
        ContractMaterialVO contractMaterialVO = new ContractMaterialVO();
        BeanUtils.copyProperties(bamuContractMaterial, contractMaterialVO);
        contractMaterialVO.setApplyCountNum(bamuContractMaterial.getApplyNum());
        contractMaterialVO.setCheckNum(bamuContractMaterial.getCheckNum());
        contractMaterialVO.setContractCount(bamuContractMaterial.getMaterialNum());
        return contractMaterialVO;
    }

    @Override
    public YResult<String> saveOrUpdate(ProjectMaterialSaveDto saveDto) {
        try {
                BamuPurchaseApplyMaterial bamuPurchaseApplyMaterial = convertDto2Dao(saveDto);
                bamuPurchaseApplyMaterialService.saveOrUpdate(bamuPurchaseApplyMaterial);
                return YResult.success(bamuPurchaseApplyMaterial.getId());
        }catch (Exception e){
            log.error("保存失败",e);
        }
        return YResult.error("保存失败");
    }

    @Override
    public YResult<String> deleteByIds(String[] ids) {
        try {
            LambdaQueryWrapper<BamuPurchaseApplyMaterial> queryWrapper = new LambdaQueryWrapper<BamuPurchaseApplyMaterial>();
            queryWrapper.in(BamuPurchaseApplyMaterial::getId,ids);
            List<BamuPurchaseApplyMaterial> applyMaterialList = bamuPurchaseApplyMaterialService.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(applyMaterialList)){
                List<BamuContractMaterial> updateContractMaterialList = new ArrayList<>();
                for (BamuPurchaseApplyMaterial bamuPurchaseApplyMaterial : applyMaterialList) {
                    BamuContractMaterial contractMaterial = iBamuContractMaterialService.getById(bamuPurchaseApplyMaterial.getContractMaterialId());
                    if (Objects.nonNull(contractMaterial)) {
                        contractMaterial.setApplyNum(ConvertUtil.getBigDecimalValue(contractMaterial.getApplyNum()).subtract(ConvertUtil.getBigDecimalValue(bamuPurchaseApplyMaterial.getOrderCount())));
                        if (contractMaterial.getApplyNum().compareTo(BigDecimal.ZERO) < 0) {
                            contractMaterial.setApplyNum(BigDecimal.ZERO);
                        }
                        updateContractMaterialList.add(contractMaterial);
                    }
                }

                if (CollectionUtils.isNotEmpty(updateContractMaterialList)){
                    iBamuContractMaterialService.saveOrUpdateBatch(updateContractMaterialList);
                }
            }

            bamuPurchaseApplyMaterialService.removeByIds(Arrays.asList(ids));
            return YResult.success("删除成功");
        }catch (Exception e){
            log.error("删除失败",e);
        }
        return YResult.error("删除失败");
    }

    @Override
    public YResult<ProjectMaterialVO> materialListCount(String orderId) {
        BamuPurchaseApplyMaterial materialSum = bamuPurchaseApplyMaterialService.getTotalByOrderId(orderId);
        if (Objects.nonNull(materialSum)){
            return YResult.success(convertDaoVo(materialSum));
        }
        return YResult.success(new ProjectMaterialVO());
    }

    private List<ProjectMaterialVO> convertDao2VoList(List<BamuPurchaseApplyMaterial> list){
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<ProjectMaterialVO> resultList = new ArrayList<>();
        for (BamuPurchaseApplyMaterial bamuPurchaseApplyMaterial : list){
            ProjectMaterialVO projectMaterialVO =convertDaoVo(bamuPurchaseApplyMaterial);
            resultList.add(projectMaterialVO);
        }
        return resultList;
    }

    private ProjectMaterialVO convertDaoVo(BamuPurchaseApplyMaterial bamuPurchaseApplyMaterial){
        ProjectMaterialVO projectMaterialVO = new ProjectMaterialVO();
        BeanUtils.copyProperties(bamuPurchaseApplyMaterial,projectMaterialVO);
        return projectMaterialVO;
    }

    /**
     * saveDto转化为dao
     */
    private BamuPurchaseApplyMaterial convertDto2Dao(ProjectMaterialSaveDto saveDto){
        BamuPurchaseApplyMaterial bamuPurchaseApplyMaterial = new BamuPurchaseApplyMaterial();
        BeanUtils.copyProperties(saveDto,bamuPurchaseApplyMaterial);
        return bamuPurchaseApplyMaterial;
    }


}
